package com.spring.demo.spring_boot.service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.spring.demo.spring_boot.domain.Role;
import com.spring.demo.spring_boot.domain.UserInfo;

/**
 * 
 * @author 王辉阳
 * @date 2017年8月15日 上午11:47:27
 * @description 认证入口，认证管理，AuthenticationManager的一个provider
 */
public class MyUserService implements UserDetailsService {
	@Autowired
	private SecurityService securityService;

	public MyUserService() {
	}

	// 登陆验证时，通过username获取用户的所有权限信息，
	// 并返回User放到spring的全局缓存SecurityContextHolder中，以供授权器使用
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		System.out.println("username is " + username);
		UserInfo users = this.securityService.findByName(username);
		if (users == null) {
			throw new UsernameNotFoundException(username);
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);

		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		return new User(users.getUserName(), users.getPassword(), enables, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths);
	}

	// 取得用户的权限
	private Set<GrantedAuthority> obtionGrantedAuthorities(UserInfo user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		// 查询所有角色
		Set<Role> roles = securityService.rolesOfUser(user.getUserId());
		// Set<Resource> tempRes = securityService.resourcesOfRoles(roles);

		for (Role role : roles) {
			authSet.add(new SimpleGrantedAuthority(role.getName()));
		}
		return authSet;
	}

}
